<template>
  <div class="piczoom">
    <div class="min-img-box">
      <img :src="url" alt="" />
      <div
        class="slider"
        v-show="showSlider"
        ref="slider"
        :style="{ left: sx + 'px', top: sy + 'px' }"
      ></div>
      <div
        class="curtain"
        ref="curtain"
        @mouseenter="mouseenter"
        @mouseleave="mouseleave"
        @mousemove="mousemove"
      ></div>
    </div>
    <div class="max-img-box" v-show="showSlider" ref="maximgbox">
      <img
        :src="url"
        alt=""
        :style="{
          left: ix + 'px',
          top: iy + 'px',
          transform: `scale(${scale})`,
        }"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Piczoom',
  props: {
    url: {
      type: String,
      default: '',
    },
    scale: {
      type: Number,
      default: 2,
    },
  },
  data() {
    return {
      showSlider: false,
      sx: 0,
      sy: 0,
      ix: 0,
      iy: 0,
    }
  },
  methods: {
    mouseenter() {
      this.showSlider = true
    },
    mouseleave() {
      this.showSlider = false
    },
    mousemove(event) {
      const { offsetX, offsetY } = event
      const { offsetWidth: sw, offsetHeight: sh } = this.$refs.slider
      const { offsetWidth: cw, offsetHeight: ch } = this.$refs.curtain
      const { offsetWidth: iw, offsetHeight: ih } = this.$refs.maximgbox
      let x = offsetX - sw / 2
      let y = offsetY - sh / 2
      if (x < 0) x = 0
      else if (x > cw - sw) x = cw - sw
      if (y < 0) y = 0
      else if (y > ch - sh) y = ch - sh
      // console.log(x, y)
      this.sx = x
      this.sy = y
      const s = this.scale
      this.ix = -iw * (s - 1) / ((cw - sw) / x)
      this.iy = -ih * (s - 1) / ((ch - sh) / y)
    },
  },
}
</script>

<style lang="scss" scoped>
.piczoom {
  position: relative;
  width: 350px;
  height: 350px;
}
.min-img-box {
  width: 100%;
  height: 100%;
}
.max-img-box {
  position: absolute;
  width: 450px;
  height: 450px;
  left: 352px;
  top: 0;
  z-index: 9999;
  overflow: hidden;
  img {
    transform-origin: 0 0;
    position: absolute;
  }
}
.slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 239px;
  height: 239px;
  background-color: #fede4f;
  opacity: 0.5;
}
.curtain {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>
